↜ Back to index Introduction to Numerical Analysis 1
Solution Lecture a4
Example solutions of Report 1.
Exercise 1
! Implementation of the midpoint method for y' = y sin t
implicit none
integer i, n
real y, h, t, f, k
= 20
n ! interval (0, 5)
= 5. / n
h
! Initial data
= 1.
y print *, 0., y
do i = 1, n
! One step of the midpoint method.
= (i - 1) * h
t = y * sin(t)
f = y + 0.5 * h * f
k = (i - 0.5) * h
t = k * sin(t)
f = y + h * f
y print *, i * h, y
enddo
end
Exercise 2
! Implementation of the backward Euler method for y' = -10(y - cos t)
implicit none
integer i, n
real y, h, t, f
= 10
n = 5. / n
h
! Initial data
= 0.
y print *, 0., y
do i = 1, n
= i * h
t = (y + 10 * h * cos(t)) / (1 + 10 * h)
y print *, t, y
enddo
end
Exercise 3
1-2 without arrays
! Implementation of the midpoint method for a system y_1' = y_2, y_2' = - y_1
implicit none
integer i, n
real h, t
real y1, y2, k1, k2
= 20
n = 10. / n
h
! Initial data
= 1.
y1 = 0.
y2 print *, 0., y1, y2
do i = 1, n
= y1 + 0.5 * h * y2
k1 = y2 + 0.5 * h * (-y1)
k2 = y1 + h * k2
y1 = y2 + h * (-k1)
y2
print *, i * h, y1, y2
enddo
end
1-2 with arrays
! Implementation of the midpoint method for a system y_1' = y_2, y_2' = - y_1
implicit none
integer i, n
real h, t
real y(2), k(2)
= 20
n = 10. / n
h
! Initial data
= [1., 0.]
y print *, 0., y
do i = 1, n
= y + 0.5 * h * [y(2), -y(1)]
k = y + h * [k(2), -k(1)]
y
print *, i * h, y
enddo
end
1-3
! Implementation of the midpoint method for the system y_1' = y_2, y_2' = - y_1
implicit none
integer i, n, m
real h, t
real y(2), k(2)
do m = 3, 10
= 2**m
n = 10. / n
h
! Initial data
= [1., 0.]
y
do i = 1, n
= y + 0.5 * h * [y(2), -y(1)]
k = y + h * [k(2), -k(1)]
y
enddo
print *, n, sqrt((y(1) - cos(10.))**2 + (y(2) + sin(10.))**2)
enddo
end
Exercise 4
! Implementation of the backward Euler method for the system y_1' = y_2, y_2' = - y_1
implicit none
integer i, n
real h, t
real y(2)
= 100
n = 10. / n
h
! Initial data
= [1., 0.]
y print *, 0., y
do i = 1, n
= (y + h * [y(2), -y(1)]) / (1 + h**2)
y
print *, i * h, y
enddo
end